package com.dzm.xgb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dzm.common.exception.Assert;
import com.dzm.common.result.ResponseEnum;
import com.dzm.xgb.core.enums.BorrowInfoStatusEnum;
import com.dzm.xgb.core.enums.BorrowerStatusEnum;
import com.dzm.xgb.core.enums.UserBindEnum;
import com.dzm.xgb.core.pojo.entity.BorrowInfo;
import com.dzm.xgb.core.mapper.BorrowInfoMapper;
import com.dzm.xgb.core.pojo.entity.Borrower;
import com.dzm.xgb.core.pojo.entity.UserInfo;
import com.dzm.xgb.core.pojo.vo.BorrowInfoApprovalVO;
import com.dzm.xgb.core.pojo.vo.BorrowerDetailVO;
import com.dzm.xgb.core.service.BorrowInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dzm.xgb.core.service.BorrowerService;
import com.dzm.xgb.core.service.LendService;
import com.dzm.xgb.core.service.UserInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author Dzm
 * @since 2024-08-27
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private BorrowerService borrowerService;

    @Autowired
    private LendService lendService;

    @Override
    public Integer getBorrowerInfoStatus(Long userId) {
        //获取用户借款信息列表，并按时间排序
        List<BorrowInfo> list = this.list(new LambdaQueryWrapper<BorrowInfo>()
                .eq(BorrowInfo::getUserId, userId)
                .orderByDesc(BorrowInfo::getUpdateTime));

        if (CollectionUtils.isEmpty(list)) {
            return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        }

        //获取最新的借款信息
        BorrowInfo borrowInfo = list.get(0);

        return borrowInfo.getStatus();
    }

    @Override
    public void saveBorrowerInfo(Long userId, BorrowInfo borrowInfo) {
        //获取当前用户信息
        UserInfo userInfo = userInfoService.getById(userId);
        Assert.isTrue(userInfo.getBindStatus().equals(UserBindEnum.BIND_OK.getStatus()), ResponseEnum.USER_NO_BIND_ERROR);
        Assert.isTrue(userInfo.getBorrowAuthStatus().equals(BorrowerStatusEnum.AUTH_OK.getStatus()), ResponseEnum.USER_NO_AMOUNT_ERROR);
        borrowInfo.setUserId(userId);

        //判断用户借款额度是否满足
        BigDecimal borrowerAmount = borrowerService.getBorrowerAmount(userId);
        Assert.isTrue(borrowerAmount.compareTo(borrowInfo.getAmount()) >= 0, ResponseEnum.USER_AMOUNT_LESS_ERROR);

        //将年利率转为小数
        BigDecimal divide = borrowInfo.getBorrowYearRate().divide(new BigDecimal(100));
        borrowInfo.setBorrowYearRate(divide);

        //借款状态更新为审核中
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());

        this.save(borrowInfo);
    }

    /**
     * 查询借款信息列表
     *
     * @return
     */
    @Override
    public List<BorrowInfo> selectList() {
        // 查询borrow_info信息
        List<BorrowInfo> list = baseMapper.selectBorrowInfoList();

        // 处理集合中的相关数据
        for (BorrowInfo bi : list) {
            HashMap<String, Object> param = new HashMap<>();

            param.put("returnMethod", borrowerService.getDictNameByDictCodeAndValue("returnMethod", bi.getReturnMethod().toString()));
            param.put("moneyUse", borrowerService.getDictNameByDictCodeAndValue("moneyUse", bi.getMoneyUse().toString()));
            param.put("status", BorrowerStatusEnum.getMsgByStatus(bi.getStatus()));

            bi.setParam(param);
        }

        return list;
    }

    @Override
    public Map<String, Object> show(Integer id) {
        // 获取借款信息
        BorrowInfo bi = this.getById(id);
        bi.getParam().put("returnMethod", borrowerService.getDictNameByDictCodeAndValue("returnMethod", bi.getReturnMethod().toString()));
        bi.getParam().put("moneyUse", borrowerService.getDictNameByDictCodeAndValue("moneyUse", bi.getMoneyUse().toString()));
        bi.getParam().put("status", BorrowerStatusEnum.getMsgByStatus(bi.getStatus()));

        // 借款人信息
        Long userId = bi.getUserId();
        Borrower borrower = borrowerService.getOne(new LambdaQueryWrapper<Borrower>()
                .eq(Borrower::getUserId, userId));
        //获取借款人详情信息
        BorrowerDetailVO detailVo = borrowerService.getDetailVo(borrower.getId());

        HashMap<String, Object> result = new HashMap<>();
        result.put("borrower", detailVo);
        result.put("borrowInfo", bi);

        return result;
    }

    @Transactional
    @Override
    public void approval(BorrowInfoApprovalVO vo) {
        Long id = vo.getId();
        BorrowInfo borrowInfo = this.getById(id);

        //状态修改
        borrowInfo.setStatus(vo.getStatus());
        this.updateById(borrowInfo);

        //如果状态是通过则产生标的
        if (borrowInfo.getStatus().equals(BorrowInfoStatusEnum.CHECK_OK.getStatus())) {
            //TODO 产生标的
            lendService.createLend(vo, borrowInfo);

        }
    }
}
